package com.hw.protocol.tool.decode;

import com.hw.protocol.tool.model.Result;
import com.hw.protocol.tool.model.entity.TxProtocol;
import com.hw.protocol.tool.view.TxUtil;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author : lihy
 * @date : 2023/8/28 10:41
 * description: 天信协议解码器
 */
@Slf4j
@Component
public class TxDecode  implements IDecode {


    @Override
    public Result decode(byte[] bytes){
        ByteBuf in = wrapBytes(bytes);

        byte[] allBts = new byte[in.readableBytes()];
        in.getBytes(0, allBts);

        byte fh = in.readByte();
        if (fh != (byte) 0xCC) {
            in.release();
            return Result.error("帧头错误");
        }

        if (!TxUtil.checkVerify(allBts)) {
            in.release();
            return Result.error("校验和错误");
        }

        TxProtocol resp = new TxProtocol();

        resp.setChildNum(in.readByte());
        resp.setFunctionCode(in.readByte());
        resp.setDataLength(in.readShortLE());
        byte[] timeBytes = new byte[7];
        in.readBytes(timeBytes);
        resp.setReadTime(TxUtil.getTime(timeBytes));
        byte[] fluxBytes = new byte[4];
        in.readBytes(fluxBytes);
        resp.setFlux(TxUtil.calculateFloat(fluxBytes));
        byte[] millionBytes = new byte[2];
        in.readBytes(millionBytes);
        byte[] volumeFloat = new byte[4];
        in.readBytes(volumeFloat);
        resp.setVolume(TxUtil.calculateMillion(millionBytes) + (long) TxUtil.calculateFloat(volumeFloat));
        byte[] tempBytes = new byte[4];
        in.readBytes(tempBytes);
        resp.setTemperature(TxUtil.calculateFloat(tempBytes));
        byte[] pressBytes = new byte[4];
        in.readBytes(pressBytes);
        resp.setPress(TxUtil.calculateFloat(pressBytes));
        byte[] alarmBytes = new byte[2];
        in.readBytes(alarmBytes);
        resp.setAlarm(alarmBytes);
        resp.setStatus(in.readByte());
        byte[] verifyBytes = new byte[2];
        in.readBytes(verifyBytes);
        resp.setVerify(verifyBytes);
        resp.setEnd(in.readByte());
        return Result.success(resp);

    }
}
